//
//  FlutterNativePhotoPlugin.m
//  Runner
//
//  Created by 小二同學 on 2020/3/25.
//  Copyright © 2020 The Chromium Authors. All rights reserved.
//

#import "FlutterNativePhotoPlugin.h"
#import "ZLPhotoBrowser.h"
#import <objc/runtime.h>

#define mainColor [UIColor colorWithRed:26/255.0 green:115/255.0 blue:232/255.0 alpha:1.0]


//定义常量 必须是C语言字符串
static char *videoUrlKey    = "videoUrlKey";
static char *fileNameKey    = "fileNameKey";
static char *outputURLKey   = "outputURLKey";
static char *resultKey      = "resultKey";
static char *controllerKey  = "controllerKey";

@interface FlutterNativePhotoPlugin()

@property (nonatomic, strong) UIViewController *controller;

@end

@implementation FlutterNativePhotoPlugin

static NSString *const CHANNELNAME = @"com.ehs2.photo_select";
static NSString *const METHODNAME  = @"selectPic";

/**
 *plugin 注册
 */
+ (void)registerWithRegistrar:(NSObject<FlutterPluginRegistrar> *)registrar {
    FlutterMethodChannel *channel = [FlutterMethodChannel methodChannelWithName:CHANNELNAME binaryMessenger:[registrar messenger]];
    
    UIViewController *viewController = [UIApplication sharedApplication].delegate.window.rootViewController;

    FlutterNativePhotoPlugin *plugin = [[FlutterNativePhotoPlugin alloc]initWithViewController:viewController];
    
    [registrar addMethodCallDelegate:plugin channel:channel];
}

/**
 *flutter端通过通道调用原生方法时会进入以下回调
 */
- (void)handleMethodCall:(FlutterMethodCall *)call result:(FlutterResult)result{
    
    NSString *methodName = call.method;
    if ([methodName isEqualToString:@"selectPic"]){
                NSDictionary *para = call.arguments;
                NSString *adress = [NSString stringWithFormat:@"%@", para[@"adress"]];
                NSInteger count = [[NSString stringWithFormat:@"%@", para[@"count"]] integerValue];
    //            NSLog(@"flutter传给原生的参数：%@", para);
                
                if (count > 0) {
                    // 图片选择
                    [self openImagePickVCWithController:self.controller adress:adress picCount:count imageArrBack:^(NSArray<NSString *> *imgPathArr) {
    //                    NSLog(@"%@", imgPathArr);
                        result(imgPathArr);
                    }];
                }else{
                    result(@[]);
                }
                
                
            }else if ([methodName isEqualToString:@"takePhoto"]){
                NSDictionary *para = call.arguments;
    //            NSLog(@"%@", para);
                NSString *adress = [NSString stringWithFormat:@"%@", para[@"adress"]];
                NSInteger count = [[NSString stringWithFormat:@"%@", para[@"count"]] integerValue];
                if (count > 0) {
                    [self takePhotoWithVC:self.controller adress:adress count:count imgPathBack:^(NSArray<NSString *> *imgPathArr) {
                        result(imgPathArr);
                    }];
                }else{
                    result(@[]);
                }
            }else if ([methodName isEqualToString:@"selectVideo"]){

            
                self.result = result;

                 [self startvideo];
            } else {
        result(FlutterMethodNotImplemented);
    }
}

// 打开相机拍照
- (void)takePhotoWithVC:(UIViewController *)vc adress:(NSString *)adress count:(NSInteger)count imgPathBack:(void(^)(NSArray <NSString *>*imgPathArr))imgPathBack{
    // 直接调用相机
    ZLCustomCamera *camera = [[ZLCustomCamera alloc] init];
    camera.modalPresentationStyle = UIModalPresentationFullScreen;
    camera.allowRecordVideo = NO;
    camera.doneBlock = ^(UIImage *image, NSURL *videoUrl) {
        
        // 获取当前日期时间
        NSDate *date = [NSDate date];
        NSDateFormatter *formatter = [[NSDateFormatter alloc] init];
        [formatter setDateFormat:@"yyyy-MM-dd HH:mm:ss"];
        // 使用formatter转换后的date字符串变成了当前时区的时间
//        NSString *dateStr = @"";//[formatter stringFromDate:date];
        NSString *dateStr = [formatter stringFromDate:date];
        
        NSDateFormatter *formatter1 = [[NSDateFormatter alloc] init];
        [formatter1 setDateFormat:@"yyyyMMddHHmmss"];
        NSString *dateStr1 = [formatter1 stringFromDate:date];
        if (!image) {
            imgPathBack(@[]);
        }
        UIImage *markImg = [self imageWithWaterMarkImage:image location:adress dateStr:dateStr];
        //压缩后的图片 大小 1024*20
        UIImage *newImg = [self compressImageSize:markImg toByte:1024*10];
        NSString *documentPath = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES).lastObject;
        NSFileManager *fileManager = [NSFileManager defaultManager];
        NSString *upLoadPath = [documentPath stringByAppendingPathComponent:@"upLoadImgCache"];
        [fileManager createDirectoryAtPath:upLoadPath withIntermediateDirectories:YES attributes:nil error:nil];
        NSString *imgPath = [upLoadPath stringByAppendingPathComponent:[NSString stringWithFormat:@"/%@cameraImg.jpg",dateStr1]];
        BOOL saveSuccess = [UIImageJPEGRepresentation(newImg, 1.0) writeToFile:imgPath atomically:YES];
        if (saveSuccess) {
            imgPathBack(@[imgPath]);
        }else{
            imgPathBack(@[]);
        }
    };
    
    [vc showDetailViewController:camera sender:nil];
}
/**
 *压缩 相机拍照的图片
 */
/*!
 *  @brief 使图片压缩后刚好小于指定大小
 *
 *  @param image 当前要压缩的图 maxLength 压缩后的大小
 *
 *  @return 图片对象
 */
//图片质量压缩到某一范围内，如果后面用到多，可以抽成分类或者工具类,这里压缩递减比二分的运行时间长，二分可以限制下限。
- (UIImage *)compressImageSize:(UIImage *)image toByte:(NSUInteger)maxLength{
    //首先判断原图大小是否在要求内，如果满足要求则不进行压缩，over
    CGFloat compression = 1;
    NSData *data = UIImageJPEGRepresentation(image, compression);
    if (data.length < maxLength) return image;
    //原图大小超过范围，先进行“压处理”，这里 压缩比 采用二分法进行处理，6次二分后的最小压缩比是0.015625，已经够小了
    CGFloat max = 1;
    CGFloat min = 0;
    for (int i = 0; i < 6; ++i) {
        compression = (max + min) / 2;
        data = UIImageJPEGRepresentation(image, compression);
        if (data.length < maxLength * 0.9) {
            min = compression;
        } else if (data.length > maxLength) {
            max = compression;
        } else {
            break;
        }
    }
    //判断“压处理”的结果是否符合要求，符合要求就over
    UIImage *resultImage = [UIImage imageWithData:data];
    if (data.length < maxLength) return resultImage;
    
    //缩处理，直接用大小的比例作为缩处理的比例进行处理，因为有取整处理，所以一般是需要两次处理
    NSUInteger lastDataLength = 0;
    while (data.length > maxLength && data.length != lastDataLength) {
        lastDataLength = data.length;
        //获取处理后的尺寸
        CGFloat ratio = (CGFloat)maxLength / data.length;
        CGSize size = CGSizeMake((NSUInteger)(resultImage.size.width * sqrtf(ratio)),
                                 (NSUInteger)(resultImage.size.height * sqrtf(ratio)));
        //通过图片上下文进行处理图片
        UIGraphicsBeginImageContext(size);
        [resultImage drawInRect:CGRectMake(0, 0, size.width, size.height)];
        resultImage = UIGraphicsGetImageFromCurrentImageContext();
        UIGraphicsEndImageContext();
        //获取处理后图片的大小
        data = UIImageJPEGRepresentation(resultImage, compression);
    }
    
    return resultImage;
}
/// 从相册中选取图片
- (void)openImagePickVCWithController:(UIViewController *)vc adress:(NSString *)adress picCount:(NSInteger)count imageArrBack:(void(^)(NSArray <NSString *>*imgPathArr))imageArrBack{
    ZLPhotoActionSheet *ac = [[ZLPhotoActionSheet alloc] init];
//    ac.configuration.allowMixSelect = NO;
    ac.configuration.allowSelectVideo = NO;
    ac.configuration.allowSelectGif = NO;
    ac.configuration.allowTakePhotoInLibrary = YES;
    ac.configuration.allowForceTouch = NO;
    ac.configuration.allowEditImage = NO;
    ac.configuration.allowSelectOriginal = YES;
    ac.configuration.navBarColor = mainColor;
    ac.configuration.navTitleColor = UIColor.whiteColor;
//    ac.configuration.bottomBtnsNormalTitleColor = mainColor;
//    ac.configuration.bottomBtnsNormalTitleColor = mainColor;
//    ac.configuration.bottomViewBgColor = UIColor.whiteColor;
//    ac.configuration.bottomBtnsNormalBgColor = mainColor;
//    ac.configuration.bottomBtnsDisableBgColor = [UIColor colorWithWhite:0.8 alpha:1.0];
//    ac.configuration.bottomBtnsNormalTitleColor = UIColor.whiteColor;
//    ac.configuration.bottomBtnsDisableTitleColor = UIColor.whiteColor;
    ac.configuration.languageType = ZLLanguageChineseSimplified;
    ac.configuration.useSystemCamera = NO;
    ac.configuration.maxPreviewCount = 0;
    ac.configuration.showCaptureImageOnTakePhotoBtn = NO;
    ac.configuration.maxSelectCount = count;
    ac.sender = vc;
    [ac setSelectImageBlock:^(NSArray<UIImage *> * _Nullable images, NSArray<PHAsset *> * _Nonnull assets, BOOL isOriginal) {
        if (images && images.count > 0) {
            // 获取当前日期时间
            NSDate *date = [NSDate date];
//            NSDateFormatter *formatter = [[NSDateFormatter alloc] init];
//            [formatter setDateFormat:@"yyyy-MM-dd HH:mm:ss"];
//            // 使用formatter转换后的date字符串变成了当前时区的时间
//            NSString *dateStr = [formatter stringFromDate:date];
            
            NSDateFormatter *formatter1 = [[NSDateFormatter alloc] init];
            [formatter1 setDateFormat:@"yyyyMMddHHmmss"];
            NSString *dateStr1 = [formatter1 stringFromDate:date];
            
            NSMutableArray *pathStrArr = [NSMutableArray array];
            // 给图片添加水印并保存相册
            for (int i = 0; i < images.count; i++) {
                UIImage *img = images[i];
                
                //UIImage *newImg = [self imageWithWaterMarkImage:img location:adress dateStr:dateStr];
                
                NSString *documentPath = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES).lastObject;
                NSFileManager *fileManager = [NSFileManager defaultManager];
                NSString *upLoadPath = [documentPath stringByAppendingPathComponent:@"upLoadImgCache"];
                [fileManager createDirectoryAtPath:upLoadPath withIntermediateDirectories:YES attributes:nil error:nil];
                NSString *imgPath = [upLoadPath stringByAppendingPathComponent:[NSString stringWithFormat:@"/%@img%d.jpg",dateStr1, i]];
                BOOL saveSuccess = [UIImageJPEGRepresentation(img, 1.0) writeToFile:imgPath atomically:YES];
                if (saveSuccess) {
                    [pathStrArr addObject:imgPath];
                }
            }
            imageArrBack(pathStrArr);
        }else{
            imageArrBack(@[]);
        }
    }];
    
    ac.cancleBlock = ^{
        imageArrBack(@[]);
    };
    [ac showPhotoLibrary];
    //    [ac showPreviewAnimated:YES];
    
}


- (UIImage *)imageWithWaterMarkImage:(UIImage *)image location:(NSString *)location dateStr:(NSString *)dateStr {
    
    UIGraphicsBeginImageContextWithOptions(image.size, NO, 0);
    //把图片画上去
    [image drawAtPoint:CGPointZero];
    
    NSDictionary *dict = @{
                           NSForegroundColorAttributeName : [UIColor redColor],
                           NSFontAttributeName : [UIFont systemFontOfSize:26.0],
                           };
    CGPoint point1 = CGPointMake(10, image.size.height - 50);
    //绘制文字到图片
    [location drawAtPoint:point1 withAttributes:dict];
    CGPoint point2 = CGPointMake(10, image.size.height - 100);
    [dateStr drawAtPoint:point2 withAttributes:dict];
    // 从上下文获取图片
    UIImage *imageWater = UIGraphicsGetImageFromCurrentImageContext();
    //关闭上下文
    UIGraphicsEndImageContext();
    return imageWater;
}

#pragma mark - 录制视频

//录制视频
- (void)startvideo
{
    UIImagePickerController *ipc = [[UIImagePickerController alloc] init];
    ipc.sourceType = UIImagePickerControllerSourceTypeCamera;//sourcetype有三种分别是camera，photoLibrary和photoAlbum
//    ipc.cameraDevice = UIImagePickerControllerCameraDeviceFront;
    NSArray *availableMedia = [UIImagePickerController availableMediaTypesForSourceType:UIImagePickerControllerSourceTypeCamera];//Camera所支持的Media格式都有哪些,共有两个分别是@"public.image",@"public.movie"
    ipc.mediaTypes = [NSArray arrayWithObject:availableMedia[1]];//设置媒体类型为public.movie
    [self.controller presentViewController:ipc animated:YES completion:nil];
    ipc.videoMaximumDuration = 10;//10秒 设置最大录制时间
    ipc.delegate = self;//设置委托

}
//此方法可以获取文件的大小，返回的是单位是KB。
- (CGFloat) getFileSize:(NSString *)path
{
    NSLog(@"我找到你了吗%@",path);
    NSFileManager *fileManager = [NSFileManager defaultManager];
    float filesize = -1.0;
    if ([fileManager fileExistsAtPath:path]) {
        NSDictionary *fileDic = [fileManager attributesOfItemAtPath:path error:nil];//获取文件的属性
        unsigned long long size = [[fileDic objectForKey:NSFileSize] longLongValue];
        filesize = 1.0*size/1024;
    }else{
        NSLog(@"找不到文件");
    }
    return filesize;
}

//此方法可以获取视频文件的时长。
- (CGFloat) getVideoLength:(NSURL *)URL
{
    AVURLAsset *avUrl = [AVURLAsset assetWithURL:URL];
    
    NSLog(@"你是什么%@",avUrl);
    
    CMTime time = [avUrl duration];
    int second = ceil(time.value/time.timescale);
    return second;
}
/**
 *UINavigationControllerDelegate
 */
//完成视频录制，并压缩后显示大小、时长
- (void)imagePickerController:(UIImagePickerController *)picker didFinishPickingMediaWithInfo:(NSDictionary *)info
{
    NSURL *sourceURL = [info objectForKey:UIImagePickerControllerMediaURL];
    NSLog(@"%@",[NSString stringWithFormat:@"%f s", [self getVideoLength:sourceURL]]);
    NSLog(@"%@", [NSString stringWithFormat:@"%.2f kb", [self getFileSize:[sourceURL path]]]);
    
    NSURL *newVideoUrl ; //一般.mp4
    NSDateFormatter *formater = [[NSDateFormatter alloc] init];//用时间给文件全名，以免重复，在测试的时候其实可以判断文件是否存在若存在，则删除，重新生成文件即可
    [formater setDateFormat:@"yyyy-MM-dd-HH:mm:ss"];
    
    
         NSString *documentPath = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES).lastObject;
         NSFileManager *fileManager = [NSFileManager defaultManager];
         NSString *upLoadPath = [documentPath stringByAppendingPathComponent:@"upLoadVideoCache"];
         [fileManager createDirectoryAtPath:upLoadPath withIntermediateDirectories:YES attributes:nil error:nil];
         NSString *imgPath = [upLoadPath stringByAppendingPathComponent:[NSString stringWithFormat:@"output-%@.mp4", [formater stringFromDate:[NSDate date]]]];
         
    
    newVideoUrl = [NSURL fileURLWithPath:imgPath] ;//这个是保存在app自己的沙盒路径里，后面可以选择是否在上传后删除掉。我建议删除掉，免得占空间。
    
    self.fileName = [NSString stringWithFormat:@"output-%@.mp4", [formater stringFromDate:[NSDate date]]];
    
    NSURL * url = [info objectForKey:UIImagePickerControllerMediaURL];
    NSString * urlStr = [url path];
    if (UIVideoAtPathIsCompatibleWithSavedPhotosAlbum(urlStr)) {
//        保存视频到相簿，注意也可以使用ALAssetsLibrary来保存
        UISaveVideoAtPathToSavedPhotosAlbum(urlStr, self, @selector(video:didFinishSavingWithError:contextInfo:), nil);
    }
    
    [picker dismissViewControllerAnimated:YES completion:nil];
    
    [self convertVideoQuailtyWithInputURL:sourceURL outputURL:newVideoUrl completeHandler:nil];
}


#pragma mark - 自定义方法
- (void)video:(NSString *)videoPath didFinishSavingWithError:(NSError *)error contextInfo:(void *)contextInfo{
    
    if (error) {
        NSLog(@"保存视频过程中发生错误，错误信息:%@",error.localizedDescription);
    } else {
        NSLog(@"视频保存成功");
        self.videoUrl = videoPath;
        NSURL * url = [NSURL fileURLWithPath:videoPath];
    }
}
#pragma mark - 压缩视频
- (void) convertVideoQuailtyWithInputURL:(NSURL*)inputURL
                               outputURL:(NSURL*)outputURL
                         completeHandler:(void (^)(AVAssetExportSession*))handler
{
    
    NSLog(@"原视频地址%@",inputURL);
    NSLog(@"改过的地址地址%@",outputURL);
    
    AVURLAsset *avAsset = [AVURLAsset URLAssetWithURL:inputURL options:nil];
    
    AVAssetExportSession *exportSession = [[AVAssetExportSession alloc] initWithAsset:avAsset presetName:AVAssetExportPresetMediumQuality];
    //  NSLog(resultPath);
    exportSession.outputURL = outputURL;
    exportSession.outputFileType = AVFileTypeMPEG4;
    exportSession.shouldOptimizeForNetworkUse= YES;
    [exportSession exportAsynchronouslyWithCompletionHandler:^(void)
     {
         switch (exportSession.status) {
             case AVAssetExportSessionStatusCancelled:
                 NSLog(@"AVAssetExportSessionStatusCancelled");
                 break;
             case AVAssetExportSessionStatusUnknown:
                 NSLog(@"AVAssetExportSessionStatusUnknown");
                 break;
             case AVAssetExportSessionStatusWaiting:
                 NSLog(@"AVAssetExportSessionStatusWaiting");
                 break;
             case AVAssetExportSessionStatusExporting:
                 NSLog(@"AVAssetExportSessionStatusExporting");
                 break;
             case AVAssetExportSessionStatusCompleted:
                 NSLog(@"AVAssetExportSessionStatusCompleted");
                 
                 
                 NSLog(@"是不是你啊%@",[NSString stringWithFormat:@"%f s", [self getVideoLength:outputURL]]);
                 
                 
                 NSLog(@"%@", [NSString stringWithFormat:@"%.2f kb", [self getFileSize:[outputURL path]]]);
                 
                 //UISaveVideoAtPathToSavedPhotosAlbum([outputURL path], self, nil, NULL);//这个是保存到手机相册
                 self.outputURL = outputURL;
                 [self alertUploadVideo:outputURL];
                 break;
             case AVAssetExportSessionStatusFailed:
                 NSLog(@"AVAssetExportSessionStatusFailed");
                 break;
         }
     }];
}

-(void)alertUploadVideo:(NSURL*)URL{
    CGFloat size = [self getFileSize:[URL path]];
    NSString *message;
    NSString *sizeString;
    CGFloat sizemb= size/1024;
    if(size<=1024){
        sizeString = [NSString stringWithFormat:@"%.2fKB",size];
    }else{
        sizeString = [NSString stringWithFormat:@"%.2fMB",sizemb];
    }
    
    if(sizemb<2){
        [self uploadVideo:URL];
    }
    
    else if(sizemb<=5){
        message = [NSString stringWithFormat:@"视频%@，大于2MB会有点慢，确定上传吗？", sizeString];
        UIAlertController * alertController = [UIAlertController alertControllerWithTitle: nil
                                                                                  message: message
                                                                           preferredStyle:UIAlertControllerStyleAlert];
        
        
        [alertController addAction:[UIAlertAction actionWithTitle:@"取消" style:UIAlertActionStyleDefault handler:^(UIAlertAction *action) {
            [[NSNotificationCenter defaultCenter] postNotificationName:@"refreshwebpages" object:nil userInfo:nil];
            [[NSFileManager defaultManager] removeItemAtPath:[URL path] error:nil];//取消之后就删除，以免占用手机硬盘空间（沙盒）
            
        }]];
        [alertController addAction:[UIAlertAction actionWithTitle:@"确定" style:UIAlertActionStyleDefault handler:^(UIAlertAction *action) {
            
            [self uploadVideo:URL];
            
        }]];
        [self.controller presentViewController:alertController animated:YES completion:nil];
        
        
    }else if(sizemb>5){
        message = [NSString stringWithFormat:@"视频%@，超过5MB，不能上传，抱歉。", sizeString];
        UIAlertController * alertController = [UIAlertController alertControllerWithTitle: nil
                                                                                  message: message
                                                                           preferredStyle:UIAlertControllerStyleAlert];
        
        [alertController addAction:[UIAlertAction actionWithTitle:@"确定" style:UIAlertActionStyleDefault handler:^(UIAlertAction *action) {
            [[NSNotificationCenter defaultCenter] postNotificationName:@"refreshwebpages" object:nil userInfo:nil];
            [[NSFileManager defaultManager] removeItemAtPath:[URL path] error:nil];//取消之后就删除，以免占用手机硬盘空间
            
        }]];
        [self.controller presentViewController:alertController animated:YES completion:nil];
    }
}

#pragma mark - 上传视频
-(void)uploadVideo:(NSURL*)URL{

//    NSMutableDictionary *dict = [NSMutableDictionary dictionary];
//
//    NSData *data = [NSData dataWithContentsOfURL:URL];
//#pragma mark - 回调数据
//    NSString *dataStr = [[NSString alloc]initWithData:data encoding:NSUTF8StringEncoding];

    NSArray<NSString *> *arr = [NSArray arrayWithObject:[URL path]];
       
    NSLog(@"视频地址%@",[URL path]);

    NSURL *url = [NSURL fileURLWithPath:[URL path]];
    
    NSLog(@"视频地址URL%@",url);
    self.result(arr);
//
//    dict[@"loanvideo"] = data;
//    dict[@"record_id"] = self.loan_record_id;
//
//    MBProgressHUD *hub = [MBProgressHUD showHUDAddedTo:self.tabBarController.view animated:YES];
//    hub.label.text = @"正在上传...";
//
//    NSString *uploadVideoUrl = [NSString stringWithFormat:@"%@%@",BaseUrl,@"uploadloanvideo"];
//
//    [[NetworkHelper shareInstance] Post:uploadVideoUrl parameter:dict data:data name:@"loanvideo" fileName:_fileName mimeType:@"video/mpeg" success:^(id responseObject) {
//        NSLog(@"视频上传成功");
//        [MBProgressHUD hideHUDForView:self.tabBarController.view animated:YES];
//        //跳回到首页
//        if ([responseObject[@"code"] integerValue] == 200) {
//
//            [self.navigationController popToRootViewControllerAnimated:YES];
//        }else if ([responseObject[@"code"] integerValue] == 501)
//        {
//            [self showAlertSureWithTitle:responseObject[@"msg"] message:nil sure:^(UIAlertAction *action) {
//                [UIApplication sharedApplication].keyWindow.rootViewController = [[ZZLNavViewController alloc] initWithRootViewController:[[ZZLLoginViewController alloc] init]];
//            }];
//        }
//        [LYWRegex showMessage:responseObject[@"msg"]];
//
//    } failure:^(NSError *error) {
//        NSLog(@"视频上传失败");
//        [MBProgressHUD hideHUDForView:self.tabBarController.view animated:YES];
//
//    }];
    
}
#pragma mark - 类别添加属性
- (void)setVideoUrl:(NSString *)videoUrl{
    objc_setAssociatedObject(self, videoUrlKey, videoUrl, OBJC_ASSOCIATION_COPY_NONATOMIC);
}
- (NSString *)videoUrl {
    
    return objc_getAssociatedObject(self, videoUrlKey);
}

- (void)setFileName:(NSString *)fileName {
    objc_setAssociatedObject(self, fileNameKey, fileName, OBJC_ASSOCIATION_COPY_NONATOMIC);
}
- (NSString *)fileName{
    return objc_getAssociatedObject(self, fileNameKey);
}

- (void)setOutputURL:(NSURL *)outputURL {
    objc_setAssociatedObject(self, outputURLKey, outputURL, OBJC_ASSOCIATION_RETAIN_NONATOMIC);
}
- (NSURL *)outputURL {
    return objc_getAssociatedObject(self, outputURLKey);
}

- (void)setResult:(FlutterResult)result {
    
    objc_setAssociatedObject(self, resultKey, result, OBJC_ASSOCIATION_COPY_NONATOMIC);

}
- (FlutterResult)result{
    return objc_getAssociatedObject(self, resultKey);
}
- (void)setController:(UIViewController *)controller {
    objc_setAssociatedObject(self, controllerKey, controller, OBJC_ASSOCIATION_RETAIN_NONATOMIC);

}
- (UIViewController *)controller{
    return objc_getAssociatedObject(self, controllerKey);
}

- (instancetype)initWithViewController:(UIViewController *)viewController {
    self = [super init];
    if (self) {
        self.controller = viewController;
    }
    return self;
}
@end
